#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'


import pymel.core as pmel
import maya.cmds as cmds
import maya.mel as mel
import os
import re
import yaml
from verexport.core import VerFbxExport, VerBakeAnimation


class ExportManagerCam():
    def __init__(self, config):
        self._config = config
        self._initData()
        try:
            cmds.loadPlugin('fbxmaya')
        except:pass

    def _initData(self):
        if os.path.isfile(self._config):
            configFile = self._config
        else:
            config_path = os.getenv("EXPORT_MANAGER_CONFIG_PATH")
            if config_path:
                configFile = os.path.join(config_path, self._config)
            else:
                configFile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config', self._config).replace('\\', '/')
        if not os.path.isfile(configFile):
            raise ValueError("config file is not exists!\n %s " % configFile)
        with open(configFile) as f:
            self._data = yaml.load(f)
            
    def getScenePice(self):
        fileName = os.path.basename(pmel.sceneName())
        sceneName = os.path.splitext(fileName)[0]
        namePart = []
        outPath = os.getenv("EXPORT_MANAGER_OUT_PATH")
        if outPath and os.path.isdir(outPath):
            outPath = outPath.replace('\\', '/')
            namePart.append(outPath)
        else:
            namePart.append(self._data['outPath'])
        namePart.extend(sceneName.split('_'))
        return [sceneName, namePart]
        
    def main(self):
        sceneName, namePart = self.getScenePice()
        frameData = self.getFrameRange()
        allCameras = self.getCameras()
        self.bakeAnim(allCameras, frameData)
        #cmds.bakeResults(allCameras, simulation=1, t=frameData, controlPoints=1)
        for cam in allCameras:
            camDataPath = '{}/{}'.format(os.path.join(*namePart), '{}_{}.fbx'.format(sceneName, cam)).replace('\\', '/')
            self.exportFbx(cam, camDataPath)
        #
        sceneFrameDataPath = '{}/{}'.format(os.path.join(*namePart), '{}.txt'.format(sceneName)).replace('\\', '/')
        self.validatePath(sceneFrameDataPath)
        self.write(sceneFrameDataPath, frameData)

    @staticmethod
    def exportFbx(nodes, outPath):
        exporter = VerFbxExport(filePath=outPath)
        exporter.exportObjects = nodes
        exporter.main()
        return
        cmdstr = """
        FBXProperty Export|IncludeGrp|Geometry|SmoothingGroups   -v true;
        FBXProperty Export|IncludeGrp|Animation -v true;
        FBXProperty Export|IncludeGrp|Animation|BakeComplexAnimation  -v true;
        FBXProperty Export|IncludeGrp|Animation|Deformation   -v true;  
        FBXProperty Export|IncludeGrp|Animation|Deformation|Skins  -v true;   
        FBXProperty Export|IncludeGrp|Animation|Deformation|Shape   -v true;   
        FBXProperty Export|IncludeGrp|Animation|ConstraintsGrp|Constraint   -v true;
        FBXProperty Export|IncludeGrp|CameraGrp|Camera -v true;
        FBXProperty Export|AdvOptGrp|AxisConvGrp|UpAxis -v "Y";
        """
        mel.eval(cmdstr)
        pmel.select(cl=1)
        pmel.select(nodes)
        cmds.file(outPath, force=1, options="v=0;", typ="FBX export", pr=1, es=1)
        
    @staticmethod
    def validatePath(filePath):
        if not os.path.isdir(os.path.dirname(filePath)):
            os.makedirs(os.path.dirname(filePath))
        #elif os.path.isfile(filePath):
        #    os.remove(filePath)
    
    @staticmethod
    def getFrameRange():
        st = cmds.playbackOptions(q=1, ast=1)
        et = cmds.playbackOptions(q=1, aet=1)
        return (st, et)
    
    @staticmethod
    def write(filePath, data):
        with open(filePath, 'w') as f:
            f.write(str(data))

    def getCameras(self):
        result = []
        regex = self._data['camera'].get('regex')
        if not regex:
            result.append(self._data['camera']['name'])
        else:
            for cam in pmel.ls(type='camera'):
                camName = cam.getParent().name()
                if re.match(regex, camName):
                    result.append(camName)
        return result
        
    @staticmethod
    def bakeAnim(nodes, frameRange=None):
        baker = VerBakeAnimation()
        baker.bakeObjects = nodes
        if frameRange:
            baker.frameRange = frameRange
        baker.main()

if __name__ == "__main__":
    em = ExportManager(config='deformationcar.yml')
    em.main()
